package com.sihan.framework.etm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.framework.exception.BusinessException;
import com.framework.model.UserDetail;
import com.framework.mybatis.Condition;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.framework.util.WebUtils;
import com.sihan.framework.etm.common.CacheOperatorInfo;
import com.sihan.framework.etm.common.CommonBiz;
import com.sihan.framework.etm.common.util.EtmWebUtil;
import com.sihan.framework.etm.dto.OrgDTO;
import com.sihan.framework.etm.entity.Org;
import com.sihan.framework.etm.entity.User;
import com.sihan.framework.etm.mapper.OrgMapper;
import com.sihan.framework.etm.service.OrgService;
import com.sihan.framework.etm.vo.OrgVO;

import java.util.*;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrgServiceImpl extends BaseServiceImpl<Org, String> implements OrgService {

    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private CommonBiz commonBiz;

    @Override
    public List<OrgVO> orgList() {
        List<Org> orgs = orgMapper.selectList(new Condition<>(new Org(false)));
        List<OrgVO> result = new ArrayList<>(orgs.size());
        for (Org org : orgs) {
            OrgVO orgVO = new OrgVO();
            BeanUtils.copyProperties(org, orgVO);
            orgVO.setName(org.getName());
            result.add(orgVO);
        }
        return result;
    }

    @Override
    public List<OrgVO> orgTree() {
        // 列出所有单位信息，parentId是顶级权限0
        String orgIds = (String) CacheOperatorInfo.getMapValue(EtmWebUtil.userId(), null);
        List<OrgVO> org = orgMapper.selectByorgIds(null);
        return listToTree(org, "id", "parentId");
    }


    /**
     * 对象List转为Tree树形结构
     */
    public final List<OrgVO> listToTree(List<OrgVO> entityList, String primaryFieldName, String parentFieldName) {
        JSONArray jsonArray = new JSONArray();
        List<Map<String, Object>> treeMap = new ArrayList<>();
        List<Map<String, Object>> listMap = JSON.parseObject(JSON.toJSONString(entityList), List.class);
        Map<String, Map<String, Object>> entityMap = new Hashtable<>();
        listMap.forEach(map -> entityMap.put(map.get(primaryFieldName).toString(), map));
        listMap.forEach(map -> {
            Object pid = map.get(parentFieldName);
            if (pid == null || StringUtils.equals(pid.toString(), "0")) {
                treeMap.add(map);
            } else {
                Map<String, Object> parentMap = entityMap.get(pid.toString());
                if (parentMap == null) {
                    treeMap.add(map);
                } else {
                    List<Map<String, Object>> children = (List<Map<String, Object>>) parentMap.get("children");
                    if (children == null) {
                        children = new ArrayList<>();
                        parentMap.put("children", children);
                    }
                    children.add(map);
                }
            }
        });
        jsonArray.addAll(treeMap);
        return jsonArray.toJavaList(OrgVO.class);
    }


    @Override
    public void saveOrg(Org org) {
        try {
            if (org.getParentId() != null) {
                // 验证父类Id(parentId)是否存在或者为顶级权限
                String parentId = org.getParentId();
                Org parentOrg = orgMapper.selectById(org.getParentId());
                if (StringUtils.isBlank(parentId)) {
                    throw new BusinessException("分类权限不存在或者不是顶级权限");
                }
                if ("0".equals(parentId)) {
                    throw new BusinessException("不能添加顶级父类");
                }
                org.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                org.setCreateTime(new Date());
                org.setCreateUser(WebUtils.username());
                org.setSort((short) (parentOrg.getSort()+ 1));
                org.setIsDep((short) (parentOrg.getIsDep() + 1));
                // 插入单位
                orgMapper.insert(org);
                //修改缓存
                commonBiz.setUserOrgIds(EtmWebUtil.userId());
            } else {
                org.setLastUpdateTime(new Date());
                org.setLastUpdateUser(WebUtils.username());
                orgMapper.updateById(org);
            }
        } catch (DuplicateKeyException e) {
            throw new BusinessException("权限名称或权限标识或Url已经存在");
        }
    }

    @Override
    @Transactional
    public void deleteOrg(List<String> orgIds) {
        for (String orgId : orgIds) {
            // 查询是否有子权限
            Org org = new Org();
            org.setIsDelete(false);
            org.setParentId(orgId);
            List<Org> sons = orgMapper.selectList(new Condition<>(org));
            if (!CollectionUtils.isEmpty(sons)) {
                throw new BusinessException("不能删除有子单位的单位");
            }
            Org org1 = orgMapper.selectById(orgId);
            if (null != org1) {
                String parentId = org1.getParentId();
                if ("0".equals(parentId)) {
                    throw new BusinessException("不能删除父级单位！");
                }
            }
            // 删除单位
            Org orgModel = new Org();
            orgModel.setId(orgId);
            orgModel.setIsDelete(true);
            orgMapper.updateById(orgModel);
            // 删除用户单位信息
//            UserOrg userOrg = new UserOrg();
//            userOrg.setIsDelete(true);
//            Condition<?> condition = new Condition<>(userOrg)
//                    .eq("org_id", orgId)
//                    .eq("is_delete", false);
//            userOrgMapper.update(condition);
        }
    }

    @Override
    public List<OrgVO> getDepByCompany(String companyId) {
        String orgIds = (String) CacheOperatorInfo.getMapValue(EtmWebUtil.userId(), null);
        List<String> li = new ArrayList<>();
        Collections.addAll(li, orgIds.split(","));
        String str = li.get(0);
        return orgMapper.recursiveChildren(companyId, str);
    }

    @Override
    public Org getOrg() {
        User user = WebUtils.user();
        return orgMapper.selectOne(new Condition<>(new Org(user.getCompanyCode(), false, (short) 0)));
    }

    @Override
    public List<OrgVO> listOrgByIdOrPId(OrgDTO dto) {
        String orgIds = (String) CacheOperatorInfo.getMapValue(EtmWebUtil.userId(), null);
        return orgMapper.listOrgByIdOrPId(dto);
    }

    /**
     * 根据当前用户获取下拉组织机构
     *
     * @return
     */
    @Override
    public List<OrgVO> queryByUser() {
        User user = WebUtils.user();
        //判断是否未父级单位 是就查询出下一级 0为父级单位
        OrgDTO orgDTO = new OrgDTO();
        orgDTO.setId(user.getOrgId());
        orgDTO.setParentId(user.getOrgId());
        return orgMapper.queryByUser(orgDTO);
    }
}
